/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.service.impl;


import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.isfd.constant.MongoDataConstant;
import com.comac.ins.isfd.constant.enums.IsfdMongoQueryLogicalOperatorEnum;
import com.comac.ins.isfd.constant.enums.IsfdMongoQueryOperatorEnum;
import com.comac.ins.isfd.domain.IsfdDatabaseMongoQuery;
import com.comac.ins.isfd.service.IIsfdDatabaseMongoService;
import com.mongodb.BasicDBObject;
import com.mongodb.client.*;
import com.mongodb.client.model.*;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Slf4j
@Service
public class IsfdDatabaseMongoServiceImpl implements IIsfdDatabaseMongoService, MongoDataConstant {

    @Autowired
    private MongoClient mongoClient;

    /**
     * 创建一个 MongoDB 集合
     *
     * @param collectionName 集合名称
     * @return 创建结果
     */
    @Override
    public void createCollection(String collectionName) {
        MongoDatabase database = mongoClient.getDatabase(DB_NAME);
        // 判断集合是否已经存在
        if (collectionExists(database, collectionName)) {
            log.error("MongoDB中表已存在: " + collectionName);
            throw new BaseException("MongoDB中表已存在: " + collectionName);
        }
        // 创建集合
        try {
            database.createCollection(collectionName);
        } catch (Exception e) {
            log.error("MongoDB中创建表失败，" + e);
            throw new BaseException("MongoDB中创建表失败，" + e);
        }
    }

    /**
     * 删除 MongoDB 集合
     *
     * @param collectionName 集合名称
     */
    @Override
    public void dropCollection(String collectionName) {
        MongoDatabase database = mongoClient.getDatabase(DB_NAME);
        // 判断集合是否存在
        if (!collectionExists(database, collectionName)) {
            log.error("删除失败，MongoDB中表[{}]不存在。", collectionName);
            throw new BaseException("删除失败，MongoDB中表不存在。");
        }
        try {
            // 获取集合
            MongoCollection<Document> collection = database.getCollection(collectionName);
            // 检查集合是否为空
            long documentCount = collection.countDocuments();
            if (documentCount > 0) {
                log.error("关联的MongoDB表[{}]中有数据，无法删除", collectionName);
                throw new BaseException("关联的MongoDB表中有数据，无法删除");
            }
            // 删除集合
            collection.drop();
            log.info("成功删除MongoDB表：" + collectionName);
        } catch (Exception e) {
            log.error("删除MongoDB表失败：" + collectionName, e);
            throw new BaseException("删除MongoDB表失败：" + e.getMessage());
        }
    }


    /**
     * 判断集合是否已存在
     *
     * @param database       数据库实例
     * @param collectionName 集合名称
     * @return 集合是否存在
     */
    private boolean collectionExists(MongoDatabase database, String collectionName) {
        for (String name : database.listCollectionNames()) {
            if (name.equals(collectionName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 插入数据到指定集合
     *
     * @param collectionName 集合名称
     * @param data           数据
     */
    @Override
    public String save(String collectionName, Map<String, Object> data) {
        MongoDatabase database = mongoClient.getDatabase(DB_NAME);
        if (!collectionExists(database, collectionName)) {
            log.error("表未创建！: " + collectionName);
            throw new BaseException("表未创建！: " + collectionName);
        }
        try {
            data.compute("_id", (k, id) -> {
                if (id instanceof ObjectId) {
                    return id; // 已经是 ObjectId，保持不变
                } else if (id instanceof String && ObjectId.isValid((String) id)) {
                    return new ObjectId((String) id); // 如果是有效的 ObjectId 字符串，转换
                } else {
                    return new ObjectId(); // 否则生成新的 ObjectId
                }
            });
            Document document = new Document(data);
            // 获取集合
            MongoCollection<Document> collection = database.getCollection(collectionName);
            // 插入数据
            collection.insertOne(document);
            // 返回生成的 ObjectId
            return document.getObjectId("_id").toString();
        } catch (Exception e) {
            log.error("数据插入失败, message: " + e.getMessage());
            throw new BaseException("数据插入失败, message: " + e.getMessage());
        }
    }

    /**
     * 根据 create_time、update_time 和 delete_flag 查询数据
     *
     * @param collectionName  集合名称
     * @param startCreateTime 开始创建时间（ISO格式，如 "2024-12-31T16:00:00Z"）
     * @param endCreateTime   结束创建时间
     * @param startUpdateTime 开始更新时间
     * @param endUpdateTime   结束更新时间
     * @param deleteFlag      删除标志（0-未删除，1-已删除，null-不筛选）
     * @param operation
     * @param pageQuery       分页参数
     * @return 查询结果列表
     */
//    @Override
//    public List<Document> findByTimeRangeAndDeleteFlag(
//        String collectionName,
//        String startCreateTime,
//        String endCreateTime,
//        String startUpdateTime,
//        String endUpdateTime,
//        Integer deleteFlag,
//        PageQuery pageQuery) {
//        try {
//            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
//            if (!collectionExists(database, collectionName)) {
//                throw new BaseException("MongoDB中表不存在: " + collectionName);
//            }
//
//            MongoCollection<Document> collection = database.getCollection(collectionName);
//
//            // 构建查询条件
//            List<Bson> conditions = new ArrayList<>();
//
//            // 处理 create_time 条件
//            if (StringUtils.isNotBlank(startCreateTime) && StringUtils.isNotBlank(endCreateTime)) {
//                conditions.add(Filters.and(
//                    Filters.gte("create_time", Instant.parse(startCreateTime)),
//                    Filters.lte("create_time", Instant.parse(endCreateTime))
//                ));
//            } else if (StringUtils.isNotBlank(startCreateTime)) {
//                conditions.add(Filters.gte("create_time", Instant.parse(startCreateTime)));
//            } else if (StringUtils.isNotBlank(endCreateTime)) {
//                conditions.add(Filters.lte("create_time", Instant.parse(endCreateTime)));
//            }
//
//            // 处理 update_time 条件
//            if (StringUtils.isNotBlank(startUpdateTime) && StringUtils.isNotBlank(endUpdateTime)) {
//                conditions.add(Filters.and(
//                    Filters.gte("update_time", Instant.parse(startUpdateTime)),
//                    Filters.lte("update_time", Instant.parse(endUpdateTime))
//                ));
//            } else if (StringUtils.isNotBlank(startUpdateTime)) {
//                conditions.add(Filters.gte("update_time", Instant.parse(startUpdateTime)));
//            } else if (StringUtils.isNotBlank(endUpdateTime)) {
//                conditions.add(Filters.lte("update_time", Instant.parse(endUpdateTime)));
//            }
//
//            // 处理 delete_flag 条件
//            if (deleteFlag != null) {
//                // 验证 deleteFlag 只能是 0 或 1
//                if (deleteFlag != 0 && deleteFlag != 1) {
//                    throw new BaseException("deleteFlag 参数值只能是 0 或 1");
//                }
//                conditions.add(Filters.eq("delete_flag", deleteFlag));
//            }
//
//            // 构建最终查询
//            Bson query = conditions.isEmpty() ? new Document() : Filters.and(conditions);
//
//            // 只有pageQuery不为null时应用分页
//            if (pageQuery != null) {
//                // 分页处理
//                Bson sortCondition = buildSortCondition(pageQuery);
//
//                // 修改分页处理逻辑
//                FindIterable<Document> iterable = collection.find(query)
//                    .sort(sortCondition);
//                int pageNumber = pageQuery.getPageNum();
//                int pageSize = pageQuery.getPageSize();
//                iterable = iterable
//                    .skip((pageNumber - 1) * pageSize)
//                    .limit(pageSize);
//            }
//
//            List<Document> results = new ArrayList<>();
//            for (Document doc : iterable) {
//                // 转换 ObjectId 为字符串
//                if (doc.containsKey("_id")) {
//                    doc.put("_id", doc.getObjectId("_id").toString());
//                }
//                results.add(doc);
//            }
//
//            return results;
//        } catch (DateTimeParseException e) {
//            log.error("时间格式解析错误，请使用ISO-8601格式（如：2024-12-31T16:00:00Z）", e);
//            throw new BaseException("时间格式不正确，请使用ISO-8601格式");
//        } catch (Exception e) {
//            log.error("根据条件查询数据失败，表名：" + collectionName, e);
//            throw new BaseException("查询数据失败：" + e.getMessage());
//        }
//    }

    @Override
    public List<Document> findByTimeRangeAndDeleteFlag(
        String collectionName,
        String startCreateTime,
        String endCreateTime,
        String startUpdateTime,
        String endUpdateTime,
        Integer deleteFlag,
        String operation, PageQuery pageQuery) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }

            MongoCollection<Document> collection = database.getCollection(collectionName);

            // 构建查询条件
            List<Bson> conditions = new ArrayList<>();

            // 操作过滤
            if (operation != null) {
                conditions.add(Filters.eq("importRecord.operation", operation));
            }

            // 处理 create_time 条件
            if (StringUtils.isNotBlank(startCreateTime) && StringUtils.isNotBlank(endCreateTime)) {
                conditions.add(Filters.and(
                    Filters.gte("importRecord.createTime", Instant.parse(startCreateTime)),
                    Filters.lte("importRecord.createTime", Instant.parse(endCreateTime))
                ));
            } else if (StringUtils.isNotBlank(startCreateTime)) {
                conditions.add(Filters.gte("importRecord.createTime", Instant.parse(startCreateTime)));
            } else if (StringUtils.isNotBlank(endCreateTime)) {
                conditions.add(Filters.lte("importRecord.createTime", Instant.parse(endCreateTime)));
            }

            // 处理 update_time 条件
            if (StringUtils.isNotBlank(startUpdateTime) && StringUtils.isNotBlank(endUpdateTime)) {
                conditions.add(Filters.and(
                    Filters.gte("importRecord.updateTime", Instant.parse(startUpdateTime)),
                    Filters.lte("importRecord.updateTime", Instant.parse(endUpdateTime))
                ));
            } else if (StringUtils.isNotBlank(startUpdateTime)) {
                conditions.add(Filters.gte("importRecord.updateTime", Instant.parse(startUpdateTime)));
            } else if (StringUtils.isNotBlank(endUpdateTime)) {
                conditions.add(Filters.lte("importRecord.updateTime", Instant.parse(endUpdateTime)));
            }

            // 处理 delete_flag 条件
            if (deleteFlag != null) {
                // 验证 deleteFlag 只能是 0 或 1
                if (deleteFlag != 0 && deleteFlag != 1) {
                    throw new BaseException("deleteFlag 参数值只能是 0 或 1");
                }
                conditions.add(Filters.eq("importRecord.delete_flag", deleteFlag));
            }

            // 构建最终查询
            Bson query = conditions.isEmpty() ? new Document() : Filters.and(conditions);

            // 初始化基础查询时添加投影
//            Bson projection = Projections.exclude("image", "decal_image");
//            FindIterable<Document> iterable = collection.find(query)
//                .projection(projection); // 新增投影设置

            // 初始化基础查询
            FindIterable<Document> iterable = collection.find(query);

            // 处理排序（无论是否分页都应用排序）
            if (pageQuery != null) {
                Bson sortCondition = buildSortCondition(pageQuery);
                iterable = iterable.sort(sortCondition);
            } else {
                // 如果没有分页参数，设置默认排序（可选）
                iterable = iterable.sort(Sorts.descending("_id"));
            }

            // 处理分页
            if (pageQuery != null) {
                int pageNumber = pageQuery.getPageNum();
                int pageSize = pageQuery.getPageSize();
                iterable = iterable
                    .skip((pageNumber - 1) * pageSize)
                    .limit(pageSize);
            }

            // 遍历结果（修正后的位置）
            List<Document> results = new ArrayList<>();
            for (Document doc : iterable) {
                if (doc.containsKey("_id")) {
                    doc.put("_id", doc.getObjectId("_id").toString());
                }

                doc.remove("importRecord");

                doc = decodeDocument(doc);

//                doc = removeImageFields(doc);

                results.add(doc);
            }

            return results;
        } catch (DateTimeParseException e) {
            log.error("时间格式解析错误，请使用ISO-8601格式（如：2024-12-31T16:00:00Z）", e);
            throw new BaseException("时间格式不正确，请使用ISO-8601格式");
        } catch (Exception e) {
            log.error("根据条件查询数据失败，表名：" + collectionName, e);
            throw new BaseException("查询数据失败：" + e.getMessage());
        }
    }

    /**
     * 移除image字段
     */
    private Document removeImageFields(Document doc) {
        Document result = new Document();
        doc.forEach((key, value) -> {
            if (!key.toLowerCase().contains("image")) {
                if (value instanceof Document) {
                    result.append(key, removeImageFields((Document) value));
                } else if (value instanceof List<?>) {
                    List<Object> list = ((List<?>) value).stream()
                        .map(item -> item instanceof Document ? removeImageFields((Document) item) : item)
                        .collect(Collectors.toList());
                    result.append(key, list);
                } else {
                    result.append(key, value);
                }
            }
        });
        return result;
    }

    /**
     * 批量插入数据到指定集合
     *
     * @param collectionName 集合名称
     * @param dataList       数据
     */
    @Override
    public List<String> saveBatch(String collectionName, List<Map<String, Object>> dataList) {
        MongoDatabase database = mongoClient.getDatabase(DB_NAME);
        if (!collectionExists(database, collectionName)) {
            log.error("表未创建！: " + collectionName);
            throw new BaseException("表未创建！: " + collectionName);
        }
        try {
            MongoCollection<Document> collection = database.getCollection(collectionName);
            List<Document> documents = new ArrayList<>();
            List<String> objectIdList = new ArrayList<>();

            for (Map<String, Object> data : dataList) {
                Object idValue = data.get("_id");

                ObjectId objectId;
                if (idValue instanceof ObjectId) {
                    objectId = (ObjectId) idValue;
                } else if (idValue instanceof String && ObjectId.isValid((String) idValue)) {
                    objectId = new ObjectId((String) idValue);
                } else {
                    throw new BaseException("非法或缺失的 _id");
                }

                data.put("_id", objectId); // 确保写入时是 ObjectId 类型
                // 检验并转换特殊字符
                Document document = encodeDocument(new Document(data));
                documents.add(document);
                objectIdList.add(objectId.toHexString());
            }

            if (documents.isEmpty()) {
                log.error("数据批量处理失败，操作列表为空！");
                throw new BaseException("数据批量处理失败，操作列表为空！");
            }

            collection.insertMany(documents);
            return objectIdList;

        } catch (Exception e) {
            log.error("数据批量插入失败, message: " + e.getMessage());
            throw new BaseException("数据插入失败, message: " + e.getMessage());
        }
    }

    /**
     * 为指定集合创建复合唯一索引
     *
     * @param collectionName 集合名称
     * @param fieldList      字段列表
     * @param isUnique
     */
    @Override
    public void createCompoundIndex(String collectionName, List<String> fieldList, boolean isUnique) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                log.error("MongoDB中表不存在: " + collectionName);
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }
            MongoCollection<Document> collection = mongoClient.getDatabase(DB_NAME).getCollection(collectionName);
            // 清除所有非默认索引
            try {
                collection.dropIndexes();
                log.info("成功清除所有非默认索引，表名：" + collectionName);
            } catch (Exception e) {
                log.error("清除所有索引失败，表名：" + collectionName, e);
                throw new BaseException("清除所有索引失败，表名：" + collectionName, e.getMessage());
            }

            // 构建复合索引的字段定义
            BasicDBObject indexKeys = new BasicDBObject();
            for (String field : fieldList) {
                indexKeys.append(field, 1); // 使用升序索引 (1)
            }
            // 设置索引为唯一
            IndexOptions options = new IndexOptions().unique(isUnique);
            // 创建索引
            collection.createIndex(indexKeys, options);
            log.info("成功创建唯一索引，表名：" + collectionName);
        } catch (Exception e) {
            log.error("MongoDB创建唯一索引失败，表名：" + collectionName, e);
            throw new BaseException("MongoDB创建唯一索引失败，表名：" + collectionName + e);
        }
    }

    /**
     * 为指定的 MongoDB 集合添加或更新校验规则。
     *
     * @param collectionName 集合名称
     * @param validationRule 校验规则（JSON Schema 格式）
     */
    @Override
    public void addValidationRule(String collectionName, Map<String, Object> validationRule) {
        MongoDatabase database = mongoClient.getDatabase(DB_NAME);
        // 检查集合是否存在
        if (!collectionExists(database, collectionName)) {
            log.error("集合未创建！: " + collectionName);
            throw new BaseException("集合未创建！: " + collectionName);
        }
        try {
            // 定义校验规则命令
            Document validationCommand = new Document("collMod", collectionName)
                .append("validator", new Document("$jsonSchema", new Document(validationRule)))
                .append("validationLevel", "strict") // 严格模式
                .append("validationAction", "error"); // 校验失败抛出错误
            // 执行校验规则更新命令
            database.runCommand(validationCommand);
            log.info("校验规则已成功添加或更新: " + collectionName);
        } catch (Exception e) {
            log.warn("校验规则添加失败, message: " + e.getMessage());
        }
    }


    @Override
    public Document findById(String collectionName, String objectIdStr) {
        MongoDatabase database = mongoClient.getDatabase(DB_NAME);
        MongoCollection<Document> collection = database.getCollection(collectionName);
        // 将传入的字符串解析为 ObjectId
        ObjectId objectId = new ObjectId(objectIdStr);
        // 构建查询条件
        Document query = new Document("_id", objectId);
        // 执行查询
        Document result = collection.find(query).first();
        if (result == null) {
            return null;
        }

        // 解码结果
        result = decodeDocument(result);

        result.put("_id", result.get("_id").toString());
        return result;
    }


    /**
     * 根据条件查询数据
     *
     * @param collectionName 集合名称
     * @param queryCondition 查询条件
     * @return 查询结果
     */
    @Override
    public List<Document> findWithIndex(String collectionName, IsfdDatabaseMongoQuery queryCondition) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }

            MongoCollection<Document> collection = database.getCollection(collectionName);

            // 分页查询
            PageQuery pageQuery = queryCondition.getPageQuery();
            int pageNumber = pageQuery.getPageNum();
            int pageSize = pageQuery.getPageSize();
            // 构建排序条件
            Bson sortCondition = buildSortCondition(pageQuery);

            // 构建查询条件
            Bson query = buildQueryCondition(queryCondition.getConditions());

            // 分页查询
            FindIterable<Document> iterable = collection.find(query)
                .sort(sortCondition)
                .skip((pageNumber - 1) * pageSize)
                .limit(pageSize);

            List<Document> results = new ArrayList<>();
            for (Document doc : iterable) {

                doc = decodeDocument(doc);

                results.add(doc);
            }

            return results;
        } catch (Exception e) {
            throw new BaseException("MongoDB查询失败: " + collectionName, e.getMessage());
        }
    }

    @Override
    public Document aggregationQueryUnique(String collectionName, IsfdDatabaseMongoQuery queryCondition) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }

            MongoCollection<Document> collection = database.getCollection(collectionName);

            // 构建聚合管道
            List<Bson> pipeline = new ArrayList<>();

            // 构建过滤条件
            List<IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition> conditions = queryCondition.getConditions();
            if (!CollectionUtils.isEmpty(conditions)) {
                // 去除重复的condition
                conditions = new ArrayList<>(new LinkedHashSet<>(conditions));
                Bson query = buildQueryCondition(conditions);  // 转换 queryCondition 为 Bson 查询条件
                pipeline.add(Aggregates.match(query));  // 添加 match 阶段
            }

            // 只取第一个结果
            pipeline.add(Aggregates.limit(1));

            // 执行聚合
            AggregateIterable<Document> iterable = collection.aggregate(pipeline);
            Document result = iterable.first();

            if (result != null) {
                result.put("_id", result.get("_id").toString());
                result.remove("importRecord");

                result = decodeDocument(result);
            }

            return result;
        } catch (Exception e) {
            log.error("MongoDB查询失败: " + collectionName, e.getMessage());
            throw new BaseException("MongoDB查询失败: " + collectionName, e.getMessage());
        }
    }

    @Override
    public List<Document> aggregationQuery(String collectionName, IsfdDatabaseMongoQuery queryCondition) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }

            MongoCollection<Document> collection = database.getCollection(collectionName);

            // 构建聚合管道
            List<Bson> pipeline = new ArrayList<>();

            // 构建过滤条件

            List<IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition> conditions = queryCondition.getConditions();
            if (!CollectionUtils.isEmpty(conditions)) {
                // 去除重复的condition
                conditions = new ArrayList<>(new LinkedHashSet<>(conditions));
                Bson query = buildQueryCondition(conditions);  // 转换 queryCondition 为 Bson 查询条件
                pipeline.add(Aggregates.match(query));  // 添加 match 阶段
            }
            // 分页查询
            PageQuery pageQuery = queryCondition.getPageQuery();
            int pageNumber = pageQuery.getPageNum();
            int pageSize = pageQuery.getPageSize();
            // 构建排序条件
            Bson sortCondition = buildSortCondition(pageQuery);
            // 添加分页
            pipeline.add(Aggregates.sort(sortCondition));
            pipeline.add(Aggregates.skip((pageNumber - 1) * pageSize));
            pipeline.add(Aggregates.limit(pageSize));

            // 执行聚合
            AggregateIterable<Document> iterable = collection.aggregate(pipeline);
            List<Document> results = new ArrayList<>();
            for (Document doc : iterable) {
                doc.put("_id", doc.get("_id").toString());
                doc.remove("importRecord");

                doc = decodeDocument(doc);

                results.add(doc);
            }
            return results;
        } catch (Exception e) {
            log.error("MongoDB查询失败: " + collectionName, e.getMessage());
            throw new BaseException("MongoDB查询失败: " + collectionName, e.getMessage());
        }
    }
    public List<Document> aggregationQueryHasRecord(String collectionName, IsfdDatabaseMongoQuery queryCondition) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }

            MongoCollection<Document> collection = database.getCollection(collectionName);

            // 构建聚合管道
            List<Bson> pipeline = new ArrayList<>();

            // 构建过滤条件
            List<IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition> conditions = queryCondition.getConditions();
            if (!CollectionUtils.isEmpty(conditions)) {
                // 去除重复的condition
                conditions = new ArrayList<>(new LinkedHashSet<>(conditions));
                Bson query = buildQueryCondition(conditions);  // 转换 queryCondition 为 Bson 查询条件
                pipeline.add(Aggregates.match(query));  // 添加 match 阶段
            }
            // 分页查询
            PageQuery pageQuery = queryCondition.getPageQuery();
            int pageNumber = pageQuery.getPageNum();
            int pageSize = pageQuery.getPageSize();
            // 构建排序条件
            Bson sortCondition = buildSortCondition(pageQuery);
            // 添加分页
            pipeline.add(Aggregates.sort(sortCondition));
            pipeline.add(Aggregates.skip((pageNumber - 1) * pageSize));
            pipeline.add(Aggregates.limit(pageSize));

            // 执行聚合
            AggregateIterable<Document> iterable = collection.aggregate(pipeline);
            List<Document> results = new ArrayList<>();
            for (Document doc : iterable) {
                doc.put("_id", doc.get("_id").toString());
//                doc.remove("importRecord");

                doc = decodeDocument(doc);

                results.add(doc);
            }
            return results;
        } catch (Exception e) {
            log.error("MongoDB查询失败: " + collectionName, e.getMessage());
            throw new BaseException("MongoDB查询失败: " + collectionName, e.getMessage());
        }
    }

    @Override
    public Long count(String collectionName, IsfdDatabaseMongoQuery queryCondition) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }

            MongoCollection<Document> collection = database.getCollection(collectionName);

            // 构建过滤条件
            List<IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition> conditions = queryCondition.getConditions();
            Bson filter = Filters.empty();
            if (!CollectionUtils.isEmpty(conditions)) {
                conditions = new ArrayList<>(new LinkedHashSet<>(conditions));
                filter = buildQueryCondition(conditions);  // 转换为 Bson
            }

            return collection.countDocuments(filter);
        } catch (Exception e) {
            log.error("MongoDB计数失败: " + collectionName, e);
            throw new BaseException("MongoDB计数失败: " + collectionName, e.getMessage());
        }
    }

    /**
     * 根据id集合查询子数据
     */
    @Override
    public List<Document> findByIds(String collectionName, List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }

        MongoDatabase database = mongoClient.getDatabase(DB_NAME);
        MongoCollection<Document> collection = database.getCollection(collectionName);

        List<ObjectId> objectIds = ids.stream()
            .filter(StringUtils::isNotBlank)
            .map(ObjectId::new)
            .collect(Collectors.toList());

        List<Document> resultList = new ArrayList<>();

        try (MongoCursor<Document> cursor = collection.find(Filters.in("_id", objectIds)).iterator()) {
            while (cursor.hasNext()) {
                Document originalDoc = cursor.next();
                Document decodedDoc = new Document();

                for (Map.Entry<String, Object> entry : originalDoc.entrySet()) {
                    String decodedKey = decodeFieldName(entry.getKey());
                    Object value = entry.getValue();

                    if (value instanceof ObjectId) {
                        decodedDoc.put(decodedKey, value.toString());
                    } else {
                        decodedDoc.put(decodedKey, value);
                    }
                }

                resultList.add(decodedDoc);
            }
        }
        return resultList;
    }


    /**
     * 显示集合的所有数据
     *
     */
    @Override
    public List<Document> findAll(String collectionName, IsfdDatabaseMongoQuery queryCondition) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }

            MongoCollection<Document> collection = database.getCollection(collectionName);

            List<Document> allResults = new ArrayList<>();
            Object lastId = null; // 上一次批次的最后一个 _id
            int batchSize = 1000;
            int totalFetched = 0;

            while (true) {
                List<Bson> pipeline = new ArrayList<>();

                // 构建基础 match 条件
                Bson baseMatch = null;
                if (queryCondition != null && !CollectionUtils.isEmpty(queryCondition.getConditions())) {
                    // 去除重复的 condition
                    List<IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition> conditions = new ArrayList<>(
                        new LinkedHashSet<>(queryCondition.getConditions()));
                    if (!CollectionUtils.isEmpty(conditions)) {
                        // 去除重复的condition
                        conditions = new ArrayList<>(new LinkedHashSet<>(conditions));
                        baseMatch = buildQueryCondition(conditions);
                    }
                }

                // 加上 _id > lastId 的条件（分页）
                if (lastId != null) {
                    Bson idCondition = Filters.gt("_id", lastId);
                    baseMatch = baseMatch != null ? Filters.and(baseMatch, idCondition) : idCondition;
                }

                if (baseMatch != null) {
                    pipeline.add(Aggregates.match(baseMatch));
                }

                // 按 _id 升序分页
                pipeline.add(Aggregates.sort(Sorts.ascending("_id")));
                pipeline.add(Aggregates.limit(batchSize));

                // 执行查询
                AggregateIterable<Document> iterable = collection.aggregate(pipeline).batchSize(batchSize)
                    .allowDiskUse(true)
                    .maxTime(30, TimeUnit.SECONDS);

                List<Document> batch = new ArrayList<>();
                for (Document doc : iterable) {
                    doc.put("_id", doc.get("_id").toString());
                    doc = decodeDocument(doc);
                    batch.add(doc);
                }

                if (batch.isEmpty()) {
                    break;
                }

                allResults.addAll(batch);
                totalFetched += batch.size();
                log.info("已加载 {} 条文档...", totalFetched);

                // 记录当前批次的最后一个 _id，作为下一批的起点
                lastId = new ObjectId(batch.get(batch.size() - 1).getString("_id"));
            }

            return allResults;

        } catch (Exception e) {
            log.error("MongoDB 全量查询失败，集合名：" + collectionName, e);
            throw new BaseException("MongoDB 全量查询失败，集合名：" + collectionName, e.getMessage());
        }
    }



    @Override
    public List<String> findAllCollectionName() {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);

            // 获取集合名称流
            MongoIterable<String> collectionNames = database.listCollectionNames();

            // 转换为List并过滤系统集合
            return StreamSupport.stream(collectionNames.spliterator(), false)
                .filter(name -> !name.startsWith("system."))
                .sorted()  // 按字母顺序排序
                .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取MongoDB集合数据失败：" , e);
            throw new BaseException("获取MongoDB集合数据失败", e.getMessage());
        }
    }

    @Override
    public List<Document> findAll(String collectionName) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                log.error("MongoDB中表不存在: " + collectionName);
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }

            MongoCollection<Document> collection = database.getCollection(collectionName);
            MongoCursor<Document> cursor = collection.find().iterator();

            List<Document> results = new ArrayList<>();
            while (cursor.hasNext()) {
                results.add(decodeDocument(cursor.next()));
            }
            return results;
        } catch (Exception e) {
            log.error("获取MongoDB集合数据失败，表名：" + collectionName, e);
            throw new BaseException("获取MongoDB集合数据失败，表名：" + collectionName, e.getMessage());
        }
    }

    @Override
    public List<Document> findAll(String collectionName, PageQuery pageQuery) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                log.error("MongoDB中表不存在: " + collectionName);
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }
            // 分页查询
            int pageNumber = pageQuery.getPageNum();
            int pageSize = pageQuery.getPageSize();
            // 构建排序条件
            Bson sortCondition = buildSortCondition(pageQuery);
            // 执行分页查询
            MongoCollection<Document> collection = database.getCollection(collectionName);
            MongoCursor<Document> cursor = collection.find()
                .sort(sortCondition)
                .skip((pageNumber - 1) * pageSize)
                .limit(pageSize)
                .iterator();

            List<Document> results = new ArrayList<>();
            while (cursor.hasNext()) {
                results.add(cursor.next());
            }
            return results;
        } catch (Exception e) {
            log.error("获取MongoDB集合数据失败，表名：" + collectionName, e);
            throw new BaseException("获取MongoDB集合数据失败，表名：" + collectionName, e.getMessage());
        }
    }

    @Override
    public Long count(String collectionName) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                log.error("MongoDB中表不存在: " + collectionName);
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }
            MongoCollection<Document> collection = database.getCollection(collectionName);
            return collection.countDocuments();

        } catch (Exception e) {
            log.error("获取MongoDB集合数据失败，表名：" + collectionName, e);
            throw new BaseException("获取MongoDB集合数据失败，表名：" + collectionName, e.getMessage());
        }
    }

    /**
     * 根据条件更新数据
     *
     * @param collectionName 集合名称
     * @param queryCondition
     * @param update         更新内容
     */
    public void update(String collectionName, IsfdDatabaseMongoQuery queryCondition, Map<String, Object> update) {
        try {
            // 获取集合
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                log.error("MongoDB中表不存在: " + collectionName);
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }
            MongoCollection<Document> collection = database.getCollection(collectionName);
            // 1. 构建查询条件
            Bson query = new Document();
            if (!CollectionUtils.isEmpty(queryCondition.getConditions())) {
                query = buildQueryCondition(queryCondition.getConditions()); // 转换条件为Bson
            }

            // 2. 构建更新操作（仅更新指定的字段）
            Document updateDoc = new Document();
            for (Map.Entry<String, Object> entry : update.entrySet()) {
                updateDoc.append(entry.getKey(), entry.getValue());
            }
            Bson updateOperation = new Document("$set", updateDoc); // 使用$set避免覆盖整个文档

            // 3. 执行批量更新（支持多文档更新）
            UpdateOptions options = new UpdateOptions().upsert(false); // 不插入新文档
            UpdateResult result = collection.updateMany(query, updateOperation, options);

            log.info("MongoDB更新完成，表名：{}，匹配数：{}，修改数：{}",
                collectionName, result.getMatchedCount(), result.getModifiedCount());

        } catch (Exception e) {
            log.error("MongoDB数据更新失败，表名：" + collectionName, e);
            throw new BaseException("MongoDB数据更新失败，表名：" + collectionName, e.getMessage());
        }
    }

    @Override
    public Boolean updateById(String collectionName, String objectIdStr, Map<String, Object> update) {
        try {
            // 获取集合
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                log.error("MongoDB中表不存在: " + collectionName);
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }
            MongoCollection<Document> collection = database.getCollection(collectionName);
            // 将字符串类型的 objectId 转换为 ObjectId
            if (StringUtils.isBlank(objectIdStr) || update == null || update.isEmpty()) {
                log.warn("更新失败: _id 为空或更新数据为空");
                return false;
            }
            Object queryId = ObjectId.isValid(objectIdStr) ? new ObjectId(objectIdStr) : objectIdStr;

            if (collection.find(new Document("_id",queryId )).first() == null) {
                log.error("MongoDB中未找到对应的 _id: " + objectIdStr);
                throw new BaseException("MongoDB中未找到对应的 _id: " + objectIdStr);
            }

            // 创建更新文档，排除 _id 字段
            Document updateDoc = new Document();
            update.forEach((key, value) -> {

                key = encodeFieldName(key);

                if (!"_id".equals(key)) updateDoc.append(key, value);
            });
            // 创建更新操作：使用 $set 进行字段更新
            UpdateResult result = collection.updateOne(new Document("_id", queryId), new Document("$set", updateDoc));
            // 执行更新操作
            return result.getMatchedCount() > 0;
        } catch (Exception e) {
            log.error("MongoDB数据更新失败，表名：" + collectionName, e);
            throw new BaseException("MongoDB数据更新失败，表名：" + collectionName + ", message: " + e.getMessage());
        }
    }


    @Override
    public boolean deleteByIds(String collectionName, List<String> objectIdStrs) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);

            // 检查集合是否存在
            if (!collectionExists(database, collectionName)) {
                throw new IllegalArgumentException("MongoDB 集合不存在: " + collectionName);
            }

            MongoCollection<Document> collection = database.getCollection(collectionName);

            // 将字符串 ID 转换为 ObjectId
            List<ObjectId> objectIds = objectIdStrs.stream()
                .map(ObjectId::new)
                .collect(Collectors.toList());

            // 执行批量删除操作
            long deletedCount = collection.deleteMany(new Document("_id", new Document("$in", objectIds))).getDeletedCount();

            return true;
        } catch (Exception e) {
            log.error("删除失败: " + e.getMessage(), e);
            throw new BaseException("删除失败：" + e.getMessage());
        }
    }

    /**
     * 构造排序条件
     */
    private Bson buildSortCondition(PageQuery pageQuery) {
        String sortField = pageQuery.getOrderByColumn();
        boolean ascending = "asc".equalsIgnoreCase(pageQuery.getIsAsc());

        if (sortField == null || sortField.isEmpty()) {
            sortField = "_id"; // 默认按 `_id` 排序
        }

        return ascending ? Sorts.ascending(sortField) : Sorts.descending(sortField);
    }

    /**
     * 构造查询条件
     */
    private Bson buildQueryCondition(List<IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition> queryConditions) {
        if (queryConditions == null || queryConditions.isEmpty()) {
            return new BasicDBObject(); // 如果没有条件，返回空查询条件
        }
        return buildLogicalOperatorQuery(queryConditions);
    }

    /**
     * 将单个查询条件转换为 Bson
     */
    private Bson buildOperatorQuery(IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition queryCondition) {
        String fieldName = queryCondition.getFieldName();
        String operator = queryCondition.getOperator();
        String value = queryCondition.getValue();
        Boolean valueNumberCheck = queryCondition.getValueNumberCheck();

        if (StringUtils.isBlank(fieldName) || StringUtils.isBlank(operator) || StringUtils.isBlank(value)) {
            log.warn("查询条件不完整, 跳过当前条件: {}", queryCondition);
            return null;
        }

        IsfdMongoQueryOperatorEnum operatorEnum = IsfdMongoQueryOperatorEnum.forValue(operator);
        if (operatorEnum == null) {
            log.warn("查询操作符不支持: {}", operator);
            return null;
        }

        Object parsedValue = "_id".equals(fieldName) ? parseIdValue(value)
            : Boolean.TRUE.equals(valueNumberCheck) ? parseStringToNumberValue(true, value)
            : value;

        return switch (operatorEnum) {
            case EQUAL -> Filters.eq(fieldName, parsedValue);
            case NOT_EQUAL -> Filters.ne(fieldName, parsedValue);
            case LESS_THAN -> Filters.lt(fieldName, parseValue(value));
            case LESS_THAN_EQUALS -> Filters.lte(fieldName, parseValue(value));
            case GREATER_THAN -> Filters.gt(fieldName, parseValue(value));
            case GREATER_THAN_EQUALS -> Filters.gte(fieldName, parseValue(value));
            case INCLUDES -> Filters.in(fieldName, "_id".equals(fieldName) ? parseIdArrayValue(value) : parseArrayValue(value));
            case NOT_INCLUDES -> Filters.nin(fieldName, "_id".equals(fieldName) ? parseIdArrayValue(value) : parseArrayValue(value));
            case LIKE -> Filters.regex(fieldName, Pattern.compile(Pattern.quote(value), Pattern.CASE_INSENSITIVE));
        };
    }



    private Object parseIdValue(String value) {
        try {
            return new ObjectId(value); // 处理 ObjectId 类型
        } catch (IllegalArgumentException e) {
            return value; // 不是 ObjectId，保持原值
        }
    }

    private List<Object> parseIdArrayValue(String value) {
        List<Object> idList = new ArrayList<>();
        for (String id : value.split(",")) {
            idList.add(parseIdValue(id.trim()));
        }
        return idList;
    }


    /**
     * 先处理 IsfdMongoQueryOperatorEnum
     * 再处理 IsfdMongoQueryLogicalOperatorEnum
     */
    private Bson buildLogicalOperatorQuery(List<IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition> conditions) {
        if (conditions == null || conditions.isEmpty()) {
            return Filters.empty();
        }

        List<Bson> andConditions = new ArrayList<>();
        List<Bson> orConditions = new ArrayList<>();

        for (IsfdDatabaseMongoQuery.IsfdDatabaseMongoQueryCondition condition : conditions) {
            Bson currentCondition = buildOperatorQuery(condition);
            if (currentCondition == null) continue;

            String logicalOperator = condition.getLogicalOperator();
            if (logicalOperator == null || logicalOperator.equalsIgnoreCase(IsfdMongoQueryLogicalOperatorEnum.AND.getValue())) {
                andConditions.add(currentCondition);
            } else if (logicalOperator.equalsIgnoreCase(IsfdMongoQueryLogicalOperatorEnum.OR.getValue())) {
                orConditions.add(currentCondition);
            }
        }

        List<Bson> finalConditions = new ArrayList<>();
        if (!andConditions.isEmpty()) {
            finalConditions.add(Filters.and(andConditions));
        }
        if (!orConditions.isEmpty()) {
            finalConditions.add(Filters.or(orConditions));
        }

        if (finalConditions.isEmpty()) {
            return Filters.empty();
        } else if (finalConditions.size() == 1) {
            return finalConditions.get(0);
        } else {
            return Filters.and(finalConditions);
        }
    }



    private Object parseStringToNumberValue(Boolean valueNumberCheck, String value) {
        if (!valueNumberCheck) {
            return value;
        }
        try {
            // 尝试解析为 Integer  范围: -2,147,483,648 到 2,147,483,647
            if (value.matches("-?\\d{1,9}")) {
                return Integer.parseInt(value);
            }
            // 尝试解析为 Long 范围: -9,223,372,036,854,775,808 到 9,223,372,036,854,775,807
            else if (value.matches("-?\\d{10,19}")) {
                return Long.parseLong(value);
            }
            // 尝试解析为 Double（包含小数点）
            else if (value.contains(".") && value.matches("-?\\d+\\.\\d+")) {
                return Double.parseDouble(value);
            }
            // 如果无法解析为数字，则返回原字符串
            else {
                return value;
            }
        } catch (NumberFormatException e) {
            // 如果解析失败，则返回原字符串
            return value;
        }
    }

    /**
     * 将字符串值解析为对应的类型
     */
    private Object parseValue(String value) {
        try {
            // 优先解析为数字
            if (value.contains(".")) {
                return Double.parseDouble(value);
            } else {
                return Long.parseLong(value);
            }
        } catch (NumberFormatException e) {
            // 如果无法解析为数字，则直接返回原字符串
            return value;
        }
    }

    /**
     * 将字符串解析为数组
     */
    private List<Object> parseArrayValue(String value) {
        // 假设数组值以逗号分隔
        return Arrays.stream(value.split(","))
            .map(this::parseValue) // 转换为适当的类型
            .collect(Collectors.toList());
    }

    /**
     * 根据条件删除数据
     */
    @Override
    public void delete(String collectionName, Map<String, Object> filter) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                log.error("MongoDB中表不存在: " + collectionName);
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }
            MongoCollection<Document> collection = database.getCollection(collectionName);
            // 根据filter 进行筛选删除
            DeleteResult deleteResult = collection.deleteMany(new Document(filter));

            long deletedCount = deleteResult.getDeletedCount();

            log.info("已删除文档数量: " + deletedCount);
        } catch (Exception e) {
            log.error("根据条件删除数据失败，表名：{}, data ：{}", collectionName, filter, e);
            throw new BaseException("根据条件删除数据失败，表名：" + collectionName, e.getMessage());
        }
    }

    @Override
    public void clearCollection(String collectionName) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            if (!collectionExists(database, collectionName)) {
                log.error("MongoDB中表不存在: " + collectionName);
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }
            MongoCollection<Document> collection = database.getCollection(collectionName);

            // 使用空的查询条件删除所有文档
            DeleteResult deleteResult = collection.deleteMany(new Document());

            long deletedCount = deleteResult.getDeletedCount();

            log.info("已清空集合 {} 中的所有数据，删除文档数量: {}", collectionName, deletedCount);
        } catch (Exception e) {
            log.error("清空集合数据失败，表名：{}", collectionName, e);
            throw new BaseException("清空集合数据失败，表名：" + collectionName, e.getMessage());
        }
    }


    /**
     * mongo的特殊字符不能占用，否则会引起报错： ".", "$"
     */

    @Override
    public Document encodeDocument(Document input) {
        Map<String, Object> result = new HashMap<>();
        for (Map.Entry<String, Object> entry : input.entrySet()) {
            // 替换字段名中的 "." 和 "$"
            String safeKey = encodeFieldName(entry.getKey());
            result.put(safeKey, entry.getValue());
        }
        return new Document(result);
    }

    private String encodeFieldName(String fieldName) {
        return fieldName.replace(".", "＿dot＿").replace("$", "＿dollar＿");
    }

    @Override
    public Document decodeDocument(Document input) {
        Map<String, Object> result = new HashMap<>();
        for (Map.Entry<String, Object> entry : input.entrySet()) {
            // 还原字段名中的 "." 和 "$"
            String originalKey = decodeFieldName(entry.getKey());
            result.put(originalKey, entry.getValue());
        }
        return new Document(result);
    }

    private String decodeFieldName(String fieldName) {
        return fieldName.replace("＿dot＿", ".").replace("＿dollar＿", "$");
    }



    @Override
    public void dropCollectionForce(String collectionName) {
        try {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);

            // 检查集合是否存在
            if (!collectionExists(database, collectionName)) {
                log.error("MongoDB中表不存在: " + collectionName);
                throw new BaseException("MongoDB中表不存在: " + collectionName);
            }

            // 直接删除集合
            database.getCollection(collectionName).drop();

            log.info("已成功删除集合: {}", collectionName);
        } catch (Exception e) {
            log.error("删除集合失败，表名：{}", collectionName, e);
            throw new BaseException("删除集合失败，表名：" + collectionName, e.getMessage());
        }
    }
}
